<template>
    <div class="crm-invoice-container">
        <el-card shadow="hover" class="mb10" v-auth="'crm:invoice:list'">
            <el-form :inline="true" :model="search">
                <el-form-item>
                    <el-select v-model="search.invoiceType" placeholder="请输入发票类型" prefix-icon="el-icon-search" class="w100">
                        <el-option 
                            v-for="item in invoiceTypes"
                            :key="item.dictValue"
                            :label="item.dictName"
                            :value="item.dictValue">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="search.invoiceTitleType" placeholder="请输入抬头类型" prefix-icon="el-icon-search" class="w100">
                        <el-option 
                            v-for="item in invoiceTitles"
                            :key="item.dictValue"
                            :label="item.dictName"
                            :value="item.dictValue">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.invoiceTitle" placeholder="请输入开票抬头" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="search.examineStatus" placeholder="请选择审核状态" multiple clearable class="w100">
                        <el-option label="草稿" value="0"></el-option>
                        <el-option label="审核中" value="1"></el-option>
                        <el-option label="通过" value="2"></el-option>
                        <el-option label="驳回" value="3"></el-option>
                        <el-option label="撤回" value="4"></el-option>
                        <el-option label="作废" value="5"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-date-picker type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-search" type="primary" @click="onTableSearch()">查询</el-button>
                    <el-button icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'crm:invoice:add'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddCrmInvoice()">新增</el-button>
            <el-button v-auth="'crm:invoice:edit'" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditCrmInvoice()" :disabled="tableData.selections.length != 1">修改</el-button>
            <el-button v-auth="'crm:invoice:remove'" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button>
            <el-table ref="tableCrmInvoiceRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column label="收支类型" width="100" prop="invoiceFlag" show-overflow-tooltip>
                    <template #default="scope">
                        <span class="color-primary" v-if="scope.row.invoiceFlag == 'RECEIVABLE'">回款</span>
                        <span class="color-warning" v-if="scope.row.invoiceFlag == 'EXPENSE'">支出</span>
                    </template>
                </el-table-column>
                <el-table-column label="发票类型" width="150" prop="invoiceType" show-overflow-tooltip :formatter="loadInvoiceType"></el-table-column>
                <el-table-column label="抬头类型" width="100" prop="invoiceTitleType" show-overflow-tooltip :formatter="loadInvoiceTitle"></el-table-column>
                <el-table-column label="发票抬头" width="250" prop="invoiceTitle" show-overflow-tooltip></el-table-column>
                <el-table-column label="发票金额" width="150" prop="invoiceAmount" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{scope.row.invoiceAmount}} 元</span>
                    </template>
                </el-table-column>
                <el-table-column label="开票日期" width="100" prop="invoiceDate" show-overflow-tooltip></el-table-column>
                <el-table-column label="发票代码" width="150" prop="invoiceCode" show-overflow-tooltip></el-table-column>
                <el-table-column label="发票号码" width="150" prop="invoiceNumber" show-overflow-tooltip></el-table-column>
                <el-table-column label="购方开户行" width="200" prop="buyerDepositBank" show-overflow-tooltip></el-table-column>
                <el-table-column label="购方开户账户" width="200" prop="buyerDepositAccount" show-overflow-tooltip></el-table-column>
                <el-table-column label="购方纳税识别号" width="200" prop="buyerTaxNumber" show-overflow-tooltip></el-table-column>
                <el-table-column label="购方开户地址" width="200" prop="buyerDepositAddress" show-overflow-tooltip></el-table-column>
                <el-table-column label="购方联系电话" width="200" prop="buyerTelephone" show-overflow-tooltip></el-table-column>
                <el-table-column label="销方开户行" width="200" prop="sellerDepositBank" show-overflow-tooltip></el-table-column>
                <el-table-column label="销方开户账户" width="200" prop="sellerDepositAccount" show-overflow-tooltip></el-table-column>
                <el-table-column label="销方开户地址" width="200" prop="sellerDepositAddress" show-overflow-tooltip></el-table-column>
                <el-table-column label="销方纳税识别号" width="200" prop="sellerTaxNumber" show-overflow-tooltip></el-table-column>
                <el-table-column label="销方联系电话" width="200" prop="sellerTelephone" show-overflow-tooltip></el-table-column>
                <el-table-column label="审核状态" prop="examineStatus" width="80" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.examineStatus == '0'" class="color-primary">草稿</span>
                        <span v-else-if="scope.row.examineStatus == '1'" class="color-warning">审核中</span>
                        <span v-else-if="scope.row.examineStatus == '2'" class="color-success">通过</span>
                        <span v-else-if="scope.row.examineStatus == '3'" class="color-danger">驳回</span>
                        <span v-else-if="scope.row.examineStatus == '4'" class="color-primary">撤回</span>
                        <span v-else-if="scope.row.examineStatus == '5'" class="color-info">作废</span>
                    </template>
                </el-table-column>
                <el-table-column label="所属用户" prop="userName" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="所属部门" prop="deptName" width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" width="180" prop="createTime" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" fixed="right" show-overflow-tooltip width="130" v-auths="['crm:invoice:info', 'crm:invoice:edit', 'crm:invoice:remove', 'crm:invoice:commited', 'crm:invoice:approved', 'crm:invoice:rejected', 'crm:invoice:canceled', 'crm:invoice:discard', 'crm:invoice:change']">
                    <template #default="scope">
                        <el-button v-auth="'crm:invoice:info'" type="primary" link @click="onOpenInfoCrmInvoice(scope.row)">详情</el-button>
                        <el-dropdown class="ml10" style="vertical-align:unset" v-auths="['crm:invoice:edit', 'crm:invoice:remove', 'crm:invoice:commited', 'crm:invoice:approved', 'crm:invoice:rejected', 'crm:invoice:canceled', 'crm:invoice:discard', 'crm:invoice:change']">
                            <span class="el-dropdown-link">
                                <el-button type="primary" link>更多 <i class="fa fa-angle-down"></i></el-button>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <div v-auth="'crm:invoice:edit'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenEditCrmInvoice(scope.row)">修改</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:invoice:remove'" v-show="['0','3','4','5'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onTabelRowDel(scope.row)">删除</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:invoice:commited'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '1')">提交</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:invoice:approved'" v-show="['1'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '2')">通过</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:invoice:rejected'" v-show="['1','2'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '3')">驳回</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:invoice:canceled'" v-show="['1'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '4')">撤回</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:invoice:discard'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '5')">作废</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:invoice:change'">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenChangeCrmInvoice(scope.row)">变更</el-button>
                                        </el-dropdown-item>
                                    </div>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
        <AddCrmInvoice ref="addCrmInvoiceRef" @submit="onTableSearch"/>
        <EditCrmInvoice ref="editCrmInvoiceRef" @submit="onTableSearch"/>
        <ChangeCrmInvoice ref="changeCrmInvoiceRef" @submit="onTableSearch"/>
        <ApproveCrmInvoice ref="approveCrmInvoiceRef" @submit="onTableSearch"/>
        <InfoCrmInvoice ref="infoCrmInvoiceRef"/>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddCrmInvoice from '/@/views/crm/invoice/addCrmInvoice.vue';
import EditCrmInvoice from '/@/views/crm/invoice/editCrmInvoice.vue';
import ChangeCrmInvoice from '/@/views/crm/invoice/changeCrmInvoice.vue';
import ApproveCrmInvoice from '/@/views/crm/invoice/approveCrmInvoice.vue';
import InfoCrmInvoice from '/@/views/crm/invoice/infoCrmInvoice.vue';
import { getCrmInvoiceList, delCrmInvoice, examineCrmInvoice } from '/@/api/crm/invoice/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
import { getDictionaryByLabel } from '/@/api/system/dictionary/index';
export default {
    name: 'crm/invoice',
    components: { AddCrmInvoice, EditCrmInvoice, ChangeCrmInvoice, InfoCrmInvoice, ApproveCrmInvoice },
    setup() {
        const tableCrmInvoiceRef = ref();
        const addCrmInvoiceRef = ref();
        const editCrmInvoiceRef = ref();
        const changeCrmInvoiceRef = ref();
        const approveCrmInvoiceRef = ref();
        const infoCrmInvoiceRef = ref();
        const state = reactive({
            invoiceTypes: [],
            invoiceTitles: [],
            search:{
                invoiceCode: undefined,
                invoiceNumber: undefined,
                invoiceDate: undefined,
                invoiceType: undefined,
                invoiceTitleType: undefined,
                invoiceTitle: undefined,
                examineStatus: [],
                startTime: '',
                endTime: '',
                orderBy: 'createTime',
				isAsc: 'desc',
                pageNum: 1,
                pageSize: 10,
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false
            }
        });

        const loadTableData = (params) => {
            const search = { ...state.search, ...params };
            const examineStatusStr = search.examineStatus.join(',');
            getCrmInvoiceList({
                ...search,
                examineStatus: examineStatusStr
            }).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableCrmInvoiceRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
            state.search.invoiceCode = undefined;
            state.search.invoiceNumber = undefined;
            state.search.invoiceDate = undefined;
            state.search.invoiceType = undefined;
            state.search.invoiceTitleType = undefined;
            state.search.invoiceTitle = undefined;
            state.search.examineStatus = [];
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        // 打开新增弹窗
        const onOpenAddCrmInvoice = (row: object) => {
            addCrmInvoiceRef.value.openDialog(row);
        };
        // 打开编辑弹窗
        const onOpenEditCrmInvoice = (row: object) => {
            row = row || state.tableData.selections[0];
            editCrmInvoiceRef.value.openDialog(row);
        };
        // 打开变更弹窗
        const onOpenChangeCrmInvoice = (row: object) => {
            row = row || state.tableData.selections[0];
            changeCrmInvoiceRef.value.openDialog(row);
        };
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的发票信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delCrmInvoice(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData();
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条发票信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delCrmInvoice([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };

        const examineStatusText = (status: String) => {
            const statusMap = {
                '0': '草稿',
                '1': '提交',
                '2': '通过',
                '3': '驳回',
                '4': '撤回',
                '5': '作废'
            };
            return statusMap[status] || '未知';
        };

        const onOpenExamineRecordStatus = (row: object, status: String) => {
            if(['1', '4', '5'].includes(status)){
                ElMessageBox.confirm(`确认【${ examineStatusText(status) }】操作吗？`, '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    examineCrmInvoice({ examineTargetId: row.id, status: status }).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('操作成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }else if('3' === status){
                ElMessageBox.prompt('请输入驳回原因：', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then((message) => {
                    if (!message.value || message.value.trim() === '') {
                        ElMessage.error('驳回原因不能为空，请重新输入！');
                    } else {
                        examineCrmInvoice({ examineTargetId: row.id, status: status, examineReason: message.value }).then((res) => {
                            if(res.code === 0){
                                ElMessage.success('操作成功');
                                loadTableData({});
                            }
                        });
                    }
                }).catch(() => {});
            }else if('2' === status){
                approveCrmInvoiceRef.value.openDialog(row);
            }
        };
        
        const onOpenInfoCrmInvoice = (row: object) => {
            row = row || state.tableData.selections[0];
            infoCrmInvoiceRef.value.openDialog(row);
        };

        const loadInvoiceType = (row, column, cellValue, index) => {
            return state.invoiceTypes.find((item) => item.dictValue == cellValue)?.dictName;
        }

        const loadInvoiceTitle = (row, column, cellValue, index) => {
            return state.invoiceTitles.find((item) => item.dictValue == cellValue)?.dictName;
        }

        // 页面加载时
        onMounted(() => {
            loadTableData({});
            getDictionaryByLabel({ dictLabel: 'crm_invoice_type' }).then((res: any) => {
                if (res.code == 0) {
                    state.invoiceTypes = res.data;
                }
            });
            getDictionaryByLabel({ dictLabel: 'crm_invoice_title' }).then((res: any) => {
                if (res.code == 0) {
                    state.invoiceTitles = res.data;
                }
            });
        });
        return {
            tableCrmInvoiceRef,
            addCrmInvoiceRef,
            editCrmInvoiceRef,
            changeCrmInvoiceRef,
            approveCrmInvoiceRef,
            infoCrmInvoiceRef,
            onTableSearch,
            onResetSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenAddCrmInvoice,
            onOpenEditCrmInvoice,
            onTabelRowsDel,
            onTabelRowDel,
            onOpenExamineRecordStatus,
            onOpenInfoCrmInvoice,
            onOpenChangeCrmInvoice,
            loadInvoiceType,
            loadInvoiceTitle,
            ...toRefs(state),
        };
    },
};
</script>